﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using AtKardesler.Cache;
using AtKardesler.Data;
namespace AtKardesler.UIProcess.Modules
{
    public class GlobalModule : IHttpModule
    {
        private static bool IsApplicationInitialized = false;
        private static bool _applicationStartupCompleted = false;
        private static object lockObj = new object();

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication _application = sender as HttpApplication;
            HttpContext _context = _application.Context;

            if (!IsApplicationInitialized)
            {
                lock (lockObj)
                {
                    if (!IsApplicationInitialized)
                    {
                        InitializeApplication(_context);
                    }
                }
            }
        }

        private bool IsWebServiceRequest(HttpContext context)
        {
            if (context.Request.Path.Contains(".asmx"))
            {
                return true;
            }
            return false;
        }

        private void LoadUserXml()
        {
            Users users = UsersPresenter.GetUsers();
            if (users != null)
            {
                CacheManager.Instance.AddItemToCache("USERS_", users);
                IsApplicationInitialized = true;
                _applicationStartupCompleted = true;
            }
            else
            {
                //TODO EKALFA Logging
                throw new Exception("Users xml could not be loaded");
            }
        }

        private void InitializeApplication(HttpContext context)
        {
            try
            {
                //if (IsWebServiceRequest(context))
                //{
                //    LoadUserXml();
                //}

                LoadUserXml();
            }
            catch (Exception ex)
            {
                //TODO EKALFA Logging
            }
        }
    }
}
